﻿using System.Runtime.InteropServices;
using System;
using System.Collections;
using System.Collections.Generic;
using UMC.Wiki.Entities;
using UMC.Web;
using UMC.Web.UI;

[assembly: UMC.Web.Apiumc]
namespace UMC.Wiki
{

    public class Utility : UMC.Data.Utility
    {

        public static WebMeta[] ContentCells(SubjectContent content)
        {
            if (String.IsNullOrEmpty(content.DataJSON))
            {
                return new WebMeta[0];
            }
            var celss = UMC.Data.JSON.Deserializes<WebMeta>(content.DataJSON) ?? new UMC.Web.WebMeta[] { };
            var webr = UMC.Web.WebResource.Instance();
            var domain = webr.WebDomain();
            foreach (var pom in celss)
            {
                var t = pom["_CellName"];
                if (String.IsNullOrEmpty(t) == false)
                {
                    pom["type"] = t;
                    pom.Remove("_CellName");
                }
                switch (pom["type"])
                {
                    case "CMSImage":
                        {
                            var value = pom.GetDictionary()["value"] as Hashtable;
                            if (value != null)
                            {
                                value.Remove("size");
                                var src = value["src"] as string;

                                if (src.Contains(domain))
                                {
                                    value["original"] = src;
                                    value["src"] = webr.ImageResolve(src, "w400", ""); // $"{src}!w400";
                                }

                            }
                            pom.Put("style", new UIStyle().Padding(10));
                        }
                        break;
                    case "CMSCode":
                        {
                            var value = pom.GetDictionary()["value"] as Hashtable;
                            if (value != null && value.ContainsKey("code"))
                            {
                                var code = value["code"] as string;
                                var type = value["type"] as string;

                                if (String.Equals("umc", type, StringComparison.CurrentCultureIgnoreCase))
                                {
                                    var clicks = UMC.Data.JSON.Deserializes<WebMeta>(code);
                                    var ls = new List<UIEventText>();
                                    foreach (var c in clicks)
                                    {
                                        // var eventText = new UIEventText();
                                        var btnText = c["text"];
                                        c.Remove("text");
                                        var cl = new UIClick();

                                        UMC.Data.IJSON json = cl;
                                        var style = new UIStyle().Size(16);
                                        if (type == "umc") style.Radius(5);
                                        var em = c.GetDictionary().GetEnumerator();
                                        while (em.MoveNext())
                                        {
                                            var key2 = em.Key as string;
                                            switch (key2)
                                            {
                                                case "bgcolor":
                                                case "background":
                                                case "background-color":
                                                    var val = (em.Value as string) ?? "";
                                                    if (val.StartsWith("#"))
                                                    {
                                                        style.Name("background-color", val);
                                                    }
                                                    else
                                                    {
                                                        style.BgColor();
                                                    }
                                                    break;
                                                case "radius":
                                                case "border-radius":
                                                    style.Name("border-radius", em.Value as string);
                                                    break;
                                                case "color":
                                                case "border-color":
                                                    style.Name(key2, em.Value as string);
                                                    break;
                                                default:
                                                    json.Read(key2, em.Value);
                                                    break;
                                            }
                                        }

                                        if ((String.IsNullOrEmpty(cl.Key) == false) || (String.IsNullOrEmpty(cl.Command) == false && String.IsNullOrEmpty(cl.Model) == false))
                                        {
                                            ls.Add(new UIEventText(btnText).Click(cl).Style(style));
                                        }
                                    }
                                    if (ls.Count > 0)
                                    {
                                        var footer = new UIButton();
                                        footer.Style.AlignCenter().Radius(5).Size(16);
                                        footer.Button(ls.ToArray());
                                        pom.Put("type", footer.Type);
                                        pom.Put("value", footer.Data);
                                        pom.Put("format", footer.Formats);
                                        pom.Put("style", footer.Style);
                                    }
                                }
                                else if (String.IsNullOrEmpty(code) == false)
                                {

                                    var cell = Data.Markdown.Highlight(code, type);
                                    pom.Put("value", cell.Data);
                                    pom.Put("format", cell.Formats);
                                    pom.Put("style", cell.Style);
                                }
                            }

                        }

                        break;
                }
            }
            return celss;
            //      ui.AddCells(celss); ;
        }

        public static UIComment Comment(Comment cm, string model, Uri uri)
        {

            int next = 0;
            var forcomdss = new List<Comment>(DataFactory.Instance().Search(new Comment { for_id = cm.Id.Value }, false, 0, out next, 500));

            return Comment(cm, forcomdss, UMC.Web.WebResource.Instance(), model, uri);

        }
        public static UIComment Comment(Comment cm, List<Comment> replys, UMC.Web.WebResource webr, string model, Uri uri)
        {

            var btnStyle = new UIStyle().Size(12).Name("icon", new UIStyle().Font("wdk").Size(18)).Color(0x666);
            var cell = new UIComment(webr.ImageResolve(uri, cm.user_id.Value, 1, 5));
            cell.Id = cm.Id.ToString();

            var image = new List<UIComment.Image>();
            cell.ImageClick(UIClick.Pager(model, "Account", new WebMeta().Put("Id", cm.user_id), true));
            cell.Style.Name("name").Click(UIClick.Pager(model, "Account", new WebMeta().Put("Id", cm.user_id)));
            var images = Utility.BitIndex(cm.ImageIndexs ?? 0);

            UMC.Data.Utility.Each(images, b =>
            {
                image.Add(new UIComment.Image
                {
                    src = webr.ImageResolve(uri, cm.Id, b, "-3", cm.ImageIndexs?.ToString()),
                    max = webr.ImageResolve(uri, cm.Id, b, "0", cm.ImageIndexs?.ToString())

                });
            });
            var nick = cm.Poster;
            if (String.IsNullOrEmpty(nick))
            {
                nick = "游客";
            }
            if (Data.Utility.IsPhone(nick))
            {
                nick = "手机客户";
            }
            cell.Desc("dff");
            var btns = new UIEventText[] { new UIEventText('\uf087', cm.Effective > 0 ? String.Format("( {0} )", cm.Effective) : "赞").Format("{icon} {text}").Style(btnStyle)
                .Click(Web.UIClick.Click(new UIClick() { Model = model, Command = "Effective" }.Send("Refer", cm.Id.ToString())))
                , new UIEventText('\uF0E5', "回复").Format("{icon} {text}").Style(btnStyle)
                .Click(Web.UIClick.Click(new UIClick() { Model = model, Command = "Comment" }.Send("Refer", cm.Id.ToString())))};
            cell.Name("name", nick)
                .Content(cm.Content);//.Name("time", );
            cell.Bottom(UMC.Data.Utility.GetDate(cm.CommentDate), btns);

            var rs = new List<UIComment.Reply>();
            var rsl = new List<UIComment.Icon>();
            foreach (var re in replys)
            {
                var ts = new UIComment.Reply { content = "{desc}", title = "{nick} 在 {time} 回复说:" };
                ts.data = new UMC.Web.WebMeta().Put("desc", re.Content).Put("time", UMC.Data.Utility.GetDate(re.CommentDate))
                    .Put("nick", re.Poster);
                rsl.Add(new UIComment.Icon { src = webr.ImageResolve(uri, re.user_id.Value, "1", 4) });
                rs.Add(ts);
            }

            if (rs.Count > 0)
            {
                cell.Replys(rs.ToArray());
            }
            cell.Images(image.ToArray());
            return cell;

        }

        public static List<UIComment> Comments(Comment[] comments, String model, Uri uri)
        {
            var forcomdss = new List<Comment>();
            var ids = new List<ulong>();
            foreach (var k in comments)
            {
                ids.Add(k.Id.Value);
            }
            forcomdss.AddRange(DataFactory.Instance().Comments(ids.ToArray()));



            var webr = UMC.Web.WebResource.Instance();
            var cells = new List<UIComment>();

            foreach (var cm in comments)
            {
                var replys = forcomdss.FindAll(g => g.for_id == cm.Id);
                cells.Add(Comment(cm, replys, webr, model, uri));
            }
            return cells;
        }
        public static ulong UInt64Parse(Guid guid)
        {
            var b = guid.ToByteArray();

            Array.Reverse(b, 0, 4);

            Array.Copy(b, 0, b, 12, 4);

            Array.Copy(b, 4, b, 10, 2);

            Array.Copy(b, 6, b, 8, 2);

            return BitConverter.ToUInt64(b, 8);
        }
        public static ulong UInt64Parse(int i, int i1)
        {

            var b = new byte[8];
            Array.Copy(BitConverter.GetBytes(i), 0, b, 0, 4);
            Array.Copy(BitConverter.GetBytes(i1), 0, b, 4, 4);
            return BitConverter.ToUInt64(b, 0);
        }

        public static int[] IntParse(ulong i)
        {

            var b = BitConverter.GetBytes(i);
            var i2 = new int[2];
            i2[0] = BitConverter.ToInt32(b, 0);
            i2[1] = BitConverter.ToInt32(b, 4);
            return i2;// BitConverter.ToUInt64(b, 0);
        }
    }
}
